package com.ygqh.baby.service.task.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.OrderStatus;
import com.ygqh.baby.ao.ReturnType;
import com.ygqh.baby.ao.WdtTradeStatus;
import com.ygqh.baby.mapper.WdtInStockItemMapper;
import com.ygqh.baby.mapper.WdtInStockMapper;
import com.ygqh.baby.mapper.WdtOrderDetailMapper;
import com.ygqh.baby.mapper.WdtOrderMapper;
import com.ygqh.baby.mapper.WdtOutStockItemMapper;
import com.ygqh.baby.mapper.WdtOutStockMapper;
import com.ygqh.baby.model.wdt.WdtDetailList;
import com.ygqh.baby.model.wdt.WdtInStockItem;
import com.ygqh.baby.model.wdt.WdtInStockItemList;
import com.ygqh.baby.model.wdt.WdtInStockOrder;
import com.ygqh.baby.model.wdt.WdtItemList;
import com.ygqh.baby.model.wdt.WdtOrderDetialReqData;
import com.ygqh.baby.model.wdt.WdtOrderDetialResData;
import com.ygqh.baby.model.wdt.WdtOrderReqData;
import com.ygqh.baby.model.wdt.WdtOrderResData;
import com.ygqh.baby.model.wdt.WdtOutStockItem;
import com.ygqh.baby.model.wdt.WdtOutStockOrder;
import com.ygqh.baby.model.wdt.WdtQueryPurchaseOrder;
import com.ygqh.baby.model.wdt.WdtQueryStockinOrder;
import com.ygqh.baby.model.wdt.WdtQueryStockoutOrder;
import com.ygqh.baby.model.wdt.WdtResult;
import com.ygqh.baby.model.wdt.WdtStorage;
import com.ygqh.baby.model.wdt.WdtTradeByMTime;
import com.ygqh.baby.po.AdminPurchase;
import com.ygqh.baby.po.AdminPurchaseDetail;
import com.ygqh.baby.po.AdminSupplier;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgOrderDetail;
import com.ygqh.baby.po.YgReturnOrder;
import com.ygqh.baby.po.YgReturnOrderDetail;
import com.ygqh.baby.service.AdminPurchaseService;
import com.ygqh.baby.service.AdminSupplierService;
import com.ygqh.baby.service.YgOrderLogService;
import com.ygqh.baby.service.YgOrderService;
import com.ygqh.baby.service.task.WdtService;
import com.ygqh.baby.service.wechat.util.MD5;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.HttpUtil;
import com.ygqh.baby.utils.MailUtil;
import com.ygqh.baby.utils.YgStringUtils;

@Service
public class WdtServiceImpl implements WdtService {
	protected final Logger logger = Logger.getLogger(this.getClass());
	@Value("${wdt.sellerId}")
	protected String SellerID;
	@Value("${wdt.interfaceId}")
	protected String InterfaceID;
	@Value("${wdt.key}")
	protected String wdt_key;
	@Value("${wdt.warehouseNO}")
	protected String warehouseNO;
	@Value("${wdt.shopName}")
	protected String shopName;
	@Value("${wdt.test.url}")
	protected String wdt_url;
	@Value("${mail.to.all}")
	protected String mailToAll;
	@Value("${mail.to.js}")
	protected String mailToJS;
	@Value("${sms.isSend}")
	protected Boolean isSend;
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private YgOrderLogService ygOrderLogService;
	@Autowired
	private WdtOrderMapper wdtOrderMapper;
	@Autowired
	private WdtOrderDetailMapper wdtOrderDetailMapper;
	@Autowired
	private WdtOutStockMapper wdtOutStockMapper;
	@Autowired
	private WdtOutStockItemMapper wdtOutStockItemMapper;
	@Autowired
	private WdtInStockMapper wdtInStockMapper;
	@Autowired
	private WdtInStockItemMapper wdtInStockItemMapper;
	@Autowired
	private AdminSupplierService adminSupplierService;
	@Autowired
	private AdminPurchaseService adminPurchaseService;
	@Autowired
	private MailUtil mailUtil;

	public WdtResult createOrder(YgOrder order) {
		WdtOrderReqData wdtOrder = new WdtOrderReqData();
		wdtOrder.setOutInFlag(3);
		wdtOrder.setIF_OrderCode(order.getOrderId().toString());
		wdtOrder.setWarehouseNO(warehouseNO);
		wdtOrder.setGoodsTotal(order.getProductPrice());
		wdtOrder.setOrderPay(order.getTotalPrice());

		BigDecimal favourableTotal = order.getManjianPrice().add(order.getNewCustomDisPrice()).add(order.getPackDisPrice()).add(order.getYouhuijuanPrice());
		wdtOrder.setFavourableTotal(favourableTotal);
		wdtOrder.setLogisticsPay(order.getExpressPrice());
		wdtOrder.setShopName(shopName);
		wdtOrder.setBuyerName(order.getReceiver());
		wdtOrder.setBuyerPostCode("");
		wdtOrder.setBuyerTel(order.getTelPhone());
		wdtOrder.setBuyerProvince(order.getProvinceName());
		wdtOrder.setBuyerCity(order.getCityName());
		wdtOrder.setBuyerDistrict(order.getAreaName());
		wdtOrder.setBuyerAdr(order.getAddress());

		List<WdtOrderDetialReqData> wdtDetails = new ArrayList<WdtOrderDetialReqData>();
		WdtItemList itemList = new WdtItemList();
		for (YgOrderDetail detail : order.getOrderDetail()) {
			WdtOrderDetialReqData wdtDetail = new WdtOrderDetialReqData();
			wdtDetail.setSku_Code(detail.getSkuCode());
			wdtDetail.setSku_Name(detail.getProductName());
			wdtDetail.setSku_Price(detail.getSalePrice());
			wdtDetail.setQty(new BigDecimal(detail.getQuantity()));
			wdtDetails.add(wdtDetail);
		}
		itemList.setItem(wdtDetails);
		wdtOrder.setItemList(itemList);

		String content = this.getContent(wdtOrder);

		String sign = this.getSign(content);

		String methodParam = this.getMethodParam("NewOrder", sign, content);

		System.out.println(methodParam);
		WdtResult result = null;
		try {
			String con_post = HttpUtil.con_post(wdt_url, methodParam);
			result = JSONObject.parseObject(con_post, WdtResult.class);
			System.out.println(con_post);
		} catch (IOException e) {
			logger.error("同步换货单到旺店通失败，orderId=" + order.getOrderId() + ";" + e.getMessage());
			e.printStackTrace();
			result = new WdtResult();
			result.setResultCode(0);
			result.setResultMsg("旺店通接口异常");
		}
		return result;
	}

	@Override
	public WdtResult createChangeOrder(YgReturnOrder order) {

		if (order.getReturnType().equals(ReturnType.Return)) {
			WdtResult result = new WdtResult();
			result.setResultCode(-1);
			result.setResultMsg("退换单不予同步");
			logger.warn(order.getReturnCode() + ";退换单不予同步到旺店通");
			return result;
		}
		WdtOrderReqData wdtOrder = new WdtOrderReqData();
		wdtOrder.setOutInFlag(3);
		wdtOrder.setIF_OrderCode(order.getReturnCode());
		wdtOrder.setWarehouseNO(warehouseNO);
		wdtOrder.setGoodsTotal(order.getProductPrice());
		wdtOrder.setOrderPay(order.getReturnPrice());
		wdtOrder.setLogisticsPay(new BigDecimal(0));

		wdtOrder.setShopName(shopName);
		wdtOrder.setBuyerName(order.getReceiver());
		wdtOrder.setBuyerPostCode("");
		wdtOrder.setBuyerTel(order.getTelPhone());
		wdtOrder.setBuyerProvince(order.getProvinceName());
		wdtOrder.setBuyerCity(order.getCityName());
		wdtOrder.setBuyerDistrict(order.getAreaName());
		wdtOrder.setBuyerAdr(order.getAddress());

		List<WdtOrderDetialReqData> wdtDetails = new ArrayList<WdtOrderDetialReqData>();
		WdtItemList itemList = new WdtItemList();
		for (YgReturnOrderDetail detail : order.getReturnOrderDetails()) {
			WdtOrderDetialReqData wdtDetail = new WdtOrderDetialReqData();
			wdtDetail.setSku_Code(detail.getSkuCode());
			wdtDetail.setSku_Price(detail.getPrice());
			wdtDetail.setQty(new BigDecimal(detail.getAmount()));
			wdtDetails.add(wdtDetail);
		}
		itemList.setItem(wdtDetails);
		wdtOrder.setItemList(itemList);

		String content = this.getContent(wdtOrder);

		String sign = this.getSign(content);

		String methodParam = this.getMethodParam("NewOrder", sign, content);

		System.out.println(methodParam);
		WdtResult result = null;
		try {
			String con_post = HttpUtil.con_post(wdt_url, methodParam);
			result = JSONObject.parseObject(con_post, WdtResult.class);
			ygOrderLogService.addOrderLog(order.getOrderId(), OrderStatus.WaitingCheck, "createChangeOrder", con_post);
			System.out.println(con_post);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("同步换货单到旺店通失败，returnCode=" + order.getReturnCode() + ";" + e.getMessage());
			result = new WdtResult();
			result.setResultCode(-1);
			result.setResultMsg("旺店通接口异常");
		}
		return result;
	}

	@Override
	public WdtResult createStockInOrder(AdminPurchase purchase) {
		WdtOrderReqData wdtOrder = new WdtOrderReqData();
		wdtOrder.setOutInFlag(2);
		wdtOrder.setIF_OrderCode(purchase.getPurchaseCode());
		wdtOrder.setWarehouseNO(warehouseNO);
		wdtOrder.setGoodsTotal(new BigDecimal(100));
		wdtOrder.setNickName(shopName);
		AdminSupplier supplier = adminSupplierService.findById(purchase.getSupplierId());

		wdtOrder.setProviderNO(supplier.getId().toString());
		wdtOrder.setProviderName(supplier.getSupplierName());
		wdtOrder.setLinkMan(supplier.getContacts());
		wdtOrder.setLinkManTel(supplier.getMobile());
		wdtOrder.setLinkManAdr(supplier.getAddress());

		List<WdtOrderDetialReqData> wdtDetails = new ArrayList<WdtOrderDetialReqData>();
		WdtItemList itemList = new WdtItemList();
		for (AdminPurchaseDetail detail : purchase.getPurchaseDetail()) {
			WdtOrderDetialReqData wdtDetail = new WdtOrderDetialReqData();
			wdtDetail.setSku_Code(detail.getSkuCode());
			wdtDetail.setSku_Name(detail.getProductName());
			wdtDetail.setSku_Price(detail.getPrice());
			wdtDetail.setQty(detail.getQuantity());
			wdtDetail.setItem_Remark(detail.getRemark());
			wdtDetails.add(wdtDetail);
		}
		itemList.setItem(wdtDetails);
		wdtOrder.setItemList(itemList);

		String content = this.getContent(wdtOrder);

		String sign = this.getSign(content);

		String methodParam = this.getMethodParam("NewOrder", sign, content);

		System.out.println(methodParam);
		WdtResult result = null;
		try {
			String con_post = HttpUtil.con_post(wdt_url, methodParam);
			result = JSONObject.parseObject(con_post, WdtResult.class);
			if (result != null && result.getResultMsg().equals("Success")) {
				adminPurchaseService.writeBackWdtPurchaseCode(purchase.getPurchaseCode(), result.getErpOrderCode());
			}
			System.out.println(con_post);
		} catch (IOException e) {
			logger.error("同步进货单单到旺店通失败;purchaseCode=" + purchase.getPurchaseCode() + ";" + e.getMessage());
			e.printStackTrace();
			result = new WdtResult();
			result.setResultCode(-1);
			result.setResultMsg("旺店通接口异常");
		}
		return result;
	}

	/**
	 * 拼接接口参数
	 * 
	 * @param method
	 * @param sign
	 * @param content
	 * @return
	 */
	private String getMethodParam(String method, String sign, String content) {
		String methodParam = "Method=" + method + "&SellerID=" + SellerID + "&InterfaceID=" + InterfaceID + "&Sign=" + sign + "&Content=" + content;
		return methodParam;
	}

	/**
	 * 获取content数据
	 * 
	 * @param object
	 * @return
	 */
	private String getContent(Object object) {
		ObjectMapper om = new ObjectMapper();
		om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		om.setSerializationInclusion(Include.NON_NULL);
		String content = "";
		try {
			content = om.writeValueAsString(object);
			System.out.println(content);
		} catch (JsonProcessingException e2) {
			e2.printStackTrace();
		}
		return content;
	}

	/**
	 * 签名
	 * 
	 * @param content
	 * @return
	 */
	private String getSign(String content) {
		String sign = (new sun.misc.BASE64Encoder()).encode(MD5.MD5Encode(content + "" + wdt_key).getBytes());
		try {
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		return sign;
	}

	@Override
	public WdtResult QueryTradeByNO(String wdtOrderCode) {

		String content = "{\"OrderCode\":\"" + wdtOrderCode + "\"}";
		// String content2 = this.getContent(wdtOrderCode);
		String sign = this.getSign(content);
		String methodParam = this.getMethodParam("QueryTradeByNO", sign, content);
		String con_post = "";
		WdtOrderResData resData = null;
		try {
			con_post = HttpUtil.con_post(wdt_url, methodParam);
			resData = JSONObject.parseObject(con_post, WdtOrderResData.class);

			System.out.println(con_post);
		} catch (IOException e) {
			e.printStackTrace();
			ygOrderLogService.addOrderLog(123456l, OrderStatus.WaitingCheck, "QueryTradeByNO", "wdtOrderCode =" + wdtOrderCode + ";" + e.getMessage()
					+ ";con_post=" + con_post);
			return resData;
		}
		return resData;
	}

	@Override
	public WdtResult QueryStorage(String skuCode, Integer pageNO, Date startTime, Date endTime) {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("WarehouseNO", warehouseNO);
		map.put("PageNO", pageNO);
		map.put("StartTime", DateConvertUtils.formatDateTime(startTime));
		map.put("EndTime", DateConvertUtils.formatDateTime(endTime));

		// String json = JsonUtils.toJson(map);
		String content = this.getContent(map);
		String sign = this.getSign(content);
		String methodParam = this.getMethodParam("QueryStorage", sign, content);
		WdtStorage storage = null;
		String con_post = "";
		try {
			con_post = HttpUtil.con_post(wdt_url, methodParam);
			Map<String, Object> result = JSONObject.parseObject(con_post, Map.class);
			if (result.get("TotalCount") != null && result.get("TotalCount") instanceof Integer) {
				storage = new WdtStorage();
				storage.setResultCode((Integer) result.get("ResultCode"));
				storage.setResultMsg((String) result.get("ResultMsg"));
				storage.setWarehouseNO((String) result.get("WarehouseNO"));
				storage.setTotalCount((Integer) result.get("TotalCount"));
			} else {

				storage = JSONObject.parseObject(con_post, WdtStorage.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage() + ";con_post=" + con_post);
		}
		return storage;
	}

	@Override
	public WdtResult QueryTradeByMTime(Date startTime, Date endTime, WdtTradeStatus tradeStatus, Integer pageNO, Integer pageSize) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("WarehouseNO", warehouseNO);
		map.put("PageNO", pageNO);
		map.put("TradeStatus", tradeStatus);
		map.put("StartTime", DateConvertUtils.formatDateTime(startTime));
		map.put("EndTime", DateConvertUtils.formatDateTime(endTime));

		String content = this.getContent(map);
		String sign = this.getSign(content);
		String methodParam = this.getMethodParam("QueryTradeByMTime", sign, content);
		WdtTradeByMTime WdtTradeByMTime = null;
		String con_post = "";
		try {
			con_post = HttpUtil.con_post(wdt_url, methodParam);
			WdtTradeByMTime = JSONObject.parseObject(con_post, WdtTradeByMTime.class);
		} catch (Exception e) {
			logger.error(e.getMessage() + ";con_post=" + con_post);
			e.printStackTrace();
		}
		return WdtTradeByMTime;
	}

	@Override
	public Message createOrderByOrderIds(List<Long> orderIds) {
		String msg = "";
		for (Long orderId : orderIds) {
			WdtResult result = null;
			try {
				YgOrder order = ygOrderService.findOrderDetailByOrderId(orderId);
				if (order.getOrderStatus().equals(OrderStatus.WaitingPay) || order.getOrderStatus().equals(OrderStatus.TradeClosed)) {
					ygOrderLogService.addOrderLog(orderId, order.getOrderStatus(), "系统同步订单", "该订单尚未付款，或已关闭，系统不予同步");
					msg += "订单编号为：" + orderId + "的订单尚未付款，或已关闭，系统不予同步;";
					continue;
				}
				result = this.createOrder(order);
				ygOrderLogService.addOrderLog(orderId, OrderStatus.WaitingSend, "系统同步订单",
						"ResultCode:" + result.getResultCode() + ";ResultMsg:" + result.getResultMsg());

				if (0 == result.getResultCode() && "Success".equals(result.getResultMsg())) {

					YgOrder ygOrder = new YgOrder();
					ygOrder.setOrderId(orderId);
					ygOrder.setWdtOrderCode(result.getErpOrderCode());
					ygOrderService.updateByOrderId(ygOrder);
				} else {
					msg += "订单编号为：" + orderId + "的同步失败," + result.getResultMsg() + ";";
					this.sendMail(orderId.toString(), result.getResultMsg(), mailToAll);
				}
			} catch (Exception e) {
				logger.error("同步订单到旺店通失败===orderid :" + orderId + "" + e.getMessage());
				ygOrderLogService.addOrderLog(orderId, OrderStatus.WaitingSend, "系统同步订单", "同步订单到旺店通失败;" + e.getMessage());
				this.sendMail(orderId.toString(), e.getMessage() + ";" + e.getLocalizedMessage(), mailToJS);
				msg += "订单编号为：" + orderId + "的订单同步失败;" + e.getMessage() + ";";
				e.printStackTrace();
				continue;
			}
		}
		if ("".equals(msg)) {
			return Message.success("成功同步订单到旺店通", null);
		}
		return Message.error(msg, "");
	}

	private void sendMail(String orderId, String msg, String to) {
		if (isSend) {
			StringBuffer str = new StringBuffer();
			str.append("<html><head><style>.table-d table{ background:#000;font-size:14px} .table-d table td{ background:#FFF} h5{width: auto;margin-right: 20px} .title{display: flex;line-height: 10px}");
			str.append("</style></head><body>");
			str.append("<div class='title'><h5>订单同步失败</h5>");
			str.append("</div><div class='table-d'>");
			str.append("<table width='800' border='0' cellspacing='1' cellpadding='0'><tr><td width='15%'>订单编号</td><td width='15%'>失败原因</td></tr>");
			str.append("<tr><td>" + orderId + "</td>");
			str.append("<td>" + msg + "</td>");
			str.append("</tr>");
			try {
				mailUtil.sendWithHtml(to.split(","), "订单同步失败", str.toString());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public int saveWdtOrder(WdtOrderResData wdtOrder) {
		wdtOrderMapper.insertSelective(wdtOrder);
		List<WdtOrderDetialResData> orderDetails = wdtOrder.getDetailList().getDetail();
		for (WdtOrderDetialResData detail : orderDetails) {
			detail.setTradeNO(wdtOrder.getTradeNO());
			this.saveWdtOrderDetail(detail);
		}
		return 1;
	}

	@Override
	public int saveWdtOrderDetail(WdtOrderDetialResData detail) {
		// TODO Auto-generated method stub
		return wdtOrderDetailMapper.insertSelective(detail);
	}

	@Override
	public WdtResult QueryStockoutOrder(Integer Type, Integer pageNO, Integer pageSize, Date startTime, Date endTime) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Type", Type);
		map.put("PageNO", pageNO);
		map.put("StartTime", DateConvertUtils.formatDateTime(startTime));
		map.put("EndTime", DateConvertUtils.formatDateTime(endTime));
		map.put("pageSize", pageSize);

		String content = this.getContent(map);
		String sign = this.getSign(content);
		String methodParam = this.getMethodParam("QueryStockoutOrder", sign, content);
		WdtQueryStockoutOrder queryStockoutOrder = null;
		String con_post = "";
		try {
			con_post = HttpUtil.con_post(wdt_url, methodParam);
			YgStringUtils.changeCharset(con_post, "utf8");
			Map result = JSONObject.parseObject(con_post, Map.class);
			Integer ResultCode = (Integer) result.get("ResultCode");
			if (ResultCode == 0) {
				int TotalCount = Integer.parseInt((String) result.get("TotalCount"));
				if (TotalCount == 0) {
					queryStockoutOrder = new WdtQueryStockoutOrder();
					queryStockoutOrder.setResultCode((Integer) result.get("ResultCode"));
					queryStockoutOrder.setResultMsg(URLEncoder.encode((String) result.get("ResultMsg")));
					queryStockoutOrder.setTotalCount(Integer.parseInt((String) result.get("TotalCount")));
				} else {

					queryStockoutOrder = JSONObject.parseObject(con_post, WdtQueryStockoutOrder.class);
				}
			} else {
				queryStockoutOrder = new WdtQueryStockoutOrder();
				queryStockoutOrder.setResultCode((Integer) result.get("ResultCode"));
				queryStockoutOrder.setResultMsg(URLEncoder.encode((String) result.get("ResultMsg")));
				queryStockoutOrder.setTotalCount((Integer) result.get("TotalCount"));
				logger.debug(con_post);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return queryStockoutOrder;
	}

	@Override
	public WdtResult QueryStockinOrder(Integer Type, Integer pageNO, Integer pageSize, Date startTime, Date endTime) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Type", Type);
		map.put("PageNO", pageNO);
		map.put("StartTime", DateConvertUtils.formatDateTime(startTime));
		map.put("EndTime", DateConvertUtils.formatDateTime(endTime));
		map.put("pageSize", pageSize);

		String content = this.getContent(map);
		String sign = this.getSign(content);
		String methodParam = this.getMethodParam("QueryStockinOrder", sign, content);
		WdtQueryStockinOrder queryStockinOrder = null;
		String con_post = "";
		try {
			con_post = HttpUtil.con_post(wdt_url, methodParam);
			Map<String, Object> result = JSONObject.parseObject(con_post, Map.class);
			Integer ResultCode = (Integer) result.get("ResultCode");
			if (ResultCode == 0) {

				int TotalCount = Integer.parseInt((String) result.get("TotalCount"));
				if (TotalCount == 0) {
					queryStockinOrder = new WdtQueryStockinOrder();
					queryStockinOrder.setResultCode((Integer) result.get("ResultCode"));
					queryStockinOrder.setResultMsg((String) result.get("ResultMsg"));
					queryStockinOrder.setTotalCount(Integer.parseInt((String) result.get("TotalCount")));
				} else {

					queryStockinOrder = JSONObject.parseObject(con_post, WdtQueryStockinOrder.class);
				}
			} else {
				queryStockinOrder = new WdtQueryStockinOrder();
				queryStockinOrder.setResultCode((Integer) result.get("ResultCode"));
				queryStockinOrder.setResultMsg((String) result.get("ResultMsg"));
				queryStockinOrder.setTotalCount((Integer) result.get("TotalCount"));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return queryStockinOrder;
	}

	@Override
	public int saveStockOutOrder(WdtOutStockOrder outStock) {
		wdtOutStockMapper.insertSelective(outStock);
		for (WdtOutStockItem item : outStock.getDetailList().getDetail()) {
			wdtOutStockItemMapper.insertSelective(item);
		}
		return 1;
	}

	@Override
	public int saveStockInOrder(WdtInStockOrder inStock) {
		wdtInStockMapper.insertSelective(inStock);
		for (WdtInStockItem item : inStock.getItemList().getItem()) {
			wdtInStockItemMapper.insertSelective(item);
		}
		return 1;
	}

	@Override
	public List<String> findStockOutOrderNOList() {
		return wdtOutStockMapper.selectStockOutOrderNOList();
	}

	@Override
	public List<String> findStockInOrderNOList() {
		return wdtInStockMapper.selectStockInOrderNoList();
	}

	@Override
	public int saveWdtOrderBatch(List<WdtOrderResData> wdtOrderList) {
		int row = 0;
		if (wdtOrderList != null && wdtOrderList.size() > 0) {

			wdtOrderMapper.saveWdtOrderBatch(wdtOrderList);
			List<WdtOrderDetialResData> detaiList = new ArrayList<WdtOrderDetialResData>();
			for (WdtOrderResData order : wdtOrderList) {
				for (WdtOrderDetialResData detail : order.getDetailList().getDetail()) {
					if (StringUtil.isBlank(order.getTradeNO())) {
						System.out.println(order.getTradeNO());
					}
					detail.setTradeNO(order.getTradeNO());
					detaiList.add(detail);
				}
			}
			if (detaiList.size() > 0) {

				wdtOrderDetailMapper.saveWdtOrderDetailBatch(detaiList);
			}
		}

		return row;
	}

	@Override
	public List<WdtOrderDetialResData> findWdtOrderDetail(String tradeNo) {
		return wdtOrderDetailMapper.findWdtOrderDetail(tradeNo);
	}

	@Override
	public int saveWdtOrderDetailBatch(List<WdtOrderDetialResData> detailList) {
		int row = 0;
		if (detailList != null && detailList.size() > 0) {
			row = wdtOrderDetailMapper.saveWdtOrderDetailBatch(detailList);
		}
		return row;
	}

	@Override
	public int saveStockOutOrderBatch(List<WdtOutStockOrder> outStockList) {
		int row = 0;
		if (outStockList != null && outStockList.size() > 0) {
			row = wdtOutStockMapper.saveStockOutOrderBatch(outStockList);

			List<WdtOutStockItem> itemList = new ArrayList<WdtOutStockItem>();
			for (WdtOutStockOrder out : outStockList) {
				for (WdtOutStockItem wdtOutStockItem : out.getDetailList().getDetail()) {
					wdtOutStockItem.setOrderNO(out.getOrderNO());
					itemList.add(wdtOutStockItem);
				}
			}
			if (itemList.size() > 0) {

				wdtOutStockItemMapper.saveStockOutItemBatch(itemList);
			}

		}
		return row;
	}

	@Override
	public int saveStockInOrderBatch(List<WdtInStockOrder> inStockList) {
		int row = 0;
		if (inStockList != null && inStockList.size() > 0) {
			wdtInStockMapper.saveStockInOrderBatch(inStockList);

			List<WdtInStockItem> itemList = new ArrayList<WdtInStockItem>();
			for (WdtInStockOrder in : inStockList) {
				for (WdtInStockItem wdtInStockItem : in.getItemList().getItem()) {
					wdtInStockItem.setOrderNO(in.getOrderNO());
					itemList.add(wdtInStockItem);
				}
			}
			if (itemList.size() > 0) {
				wdtInStockItemMapper.saveStockInItemBatch(itemList);
			}
		}
		return row;
	}

	@Override
	public List<WdtOrderResData> findWdtOrderList() {
		return wdtOrderMapper.find();
	}

	@Override
	public List<String> findWdtOrderNoList() {
		return wdtOrderMapper.selectWdtOrderNoList();
	}

	@Override
	public int updateWdtOrderBatch(List<WdtOrderResData> orderList) {
		if (orderList != null && orderList.size() > 0) {
			List<String> tradeNoList = new ArrayList<String>();
			List<WdtOrderDetialResData> detailList = new ArrayList<WdtOrderDetialResData>();

			wdtOrderMapper.updateWdtOrderBatch(orderList);
			for (WdtOrderResData wdtOrder : orderList) {
				for (WdtOrderDetialResData detail : wdtOrder.getDetailList().getDetail()) {
					detail.setTradeNO(wdtOrder.getTradeNO());
				}
				List<WdtOrderDetialResData> orderDetail = wdtOrderDetailMapper.findWdtOrderDetail(wdtOrder.getTradeNO());
				if (wdtOrder.getDetailList().getDetail().size() != orderDetail.size()) {
					tradeNoList.add(wdtOrder.getTradeNO());
					detailList.addAll(wdtOrder.getDetailList().getDetail());
				}
			}
			if (tradeNoList.size() > 0) {
				wdtOrderDetailMapper.deleteByTradeNO(tradeNoList);
				wdtOrderDetailMapper.saveWdtOrderDetailBatch(detailList);
				return 1;
			}
		}
		return 0;
	}

	@Override
	public WdtOrderResData findWdtOrderByTradeNo(String tradeNo) {
		WdtOrderResData wdtOrderResData = wdtOrderMapper.selectByTradeNo(tradeNo);
		if (wdtOrderResData != null) {
			List<WdtOrderDetialResData> details = wdtOrderDetailMapper.selectByTradeNo(tradeNo);
			WdtDetailList list = new WdtDetailList();
			list.setDetail(details);
			wdtOrderResData.setDetailList(list);
		}
		return wdtOrderResData;
	}

	@Override
	public WdtResult queryPurchaseOrder(String purchaseNO, Date startTime, Date endTime, int CurStatus, Integer pageNO, Integer pageSize) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("PageNO", pageNO);
		// map.put("CurStatus", CurStatus);
		map.put("StartTime", DateConvertUtils.formatDateTime(startTime));
		map.put("EndTime", DateConvertUtils.formatDateTime(endTime));

		// String json = JsonUtils.toJson(map);
		String content = this.getContent(map);
		String sign = this.getSign(content);
		String methodParam = this.getMethodParam("QueryPurchaseOrder", sign, content);
		WdtStorage storage = null;
		String con_post = "";
		WdtQueryPurchaseOrder purchaseOrderList = null;
		try {
			con_post = HttpUtil.con_post(wdt_url, methodParam);
			purchaseOrderList = JSONObject.parseObject(con_post, WdtQueryPurchaseOrder.class);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return purchaseOrderList;
	}

	@Override
	public WdtResult CancelOrder(String OrderCode, int OrderType, String Reason, int log) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("OrderCode", OrderCode);
		map.put("OrderType", OrderType);
		map.put("Reason", Reason);
		map.put("log", log);

		String content = this.getContent(map);
		String sign = this.getSign(content);
		String methodParam = this.getMethodParam("CancelOrder", sign, content);
		String con_post = "";
		WdtResult result = null;
		try {
			con_post = HttpUtil.con_post(wdt_url, methodParam);
			result = JSONObject.parseObject(con_post, WdtResult.class);

			System.out.println(con_post);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public WdtInStockOrder findStockInByPurchaseNo(String purchaseNo) {
		// TODO Auto-generated method stub
		WdtInStockOrder in = wdtInStockMapper.selectStockInByPurchaseNo(purchaseNo);
		List<WdtInStockItem> itemList = wdtInStockItemMapper.selectStockInItemByOrderNO(in.getOrderNO());
		WdtInStockItemList list = new WdtInStockItemList();
		list.setItem(itemList);
		in.setItemList(list);
		// adminPurchaseService.writeBackStorageStatus(in);

		return in;

	}

	@Override
	public List<Map<String, Object>> selectNoSendOrder(Date startDate, Date endDate) {

		return wdtOutStockMapper.selectNoSendOrder(startDate, endDate);
	}

	@Override
	public List<Map<String, Object>> selectPurchaseNoInstock(Date startDate, Date endDate) {
		return wdtInStockMapper.selectPurchaseNoInstock(startDate, endDate);
	}

}
